let currentPage = 1;
const pageSize = 8;
let paginationData = {}; // 新增全局变量保存分页数据
let currentEditId = null;

let currentConsultPage = 1;
const consultPageSize = 10;
let currentPatientId = null;

let paginationDataConsult = {}; // 存储就诊分页数据

let clickTimer = null;

let regionOptions = []; // 存储部位选项
let currentConsultationData = []; // 存储当前编辑的就诊数据

let currentConsultationId = null; // 当前编辑的就诊记录ID
let currentEditDetails = [];      // 当前编辑的详情数据

// 初始化加载数据
window.onload = function() {
    loadData();
    loadRegions(); // 新增初始化部位列表
};

// 获取部位列表
async function loadRegions() {
    try {
        const response = await fetch('/junxingtang/patient/getRegionList');
        const result = await response.json();
        if (result.code === 200) {
            regionOptions = result.data;
            initRegionSelect();
        }
    } catch (error) {
        console.error('获取部位列表失败:', error);
    }
}

// 初始化下拉框
function initRegionSelect() {
    const container  = document.getElementById('regionOptions');
    container.innerHTML = regionOptions.map(region => `
        <div class="option-item" data-value="${region.regionCode}">
            ${region.regionName}
        </div>
    `).join('');

    // 点击选项切换选中
    container.querySelectorAll('.option-item').forEach(item => {
        item.addEventListener('click', (e) => {
            e.stopPropagation();
            item.classList.toggle('selected');
            updateSelectedRegions();
        });
    });
}

// 初始化编辑弹窗的下拉选项
function initEditRegionSelect() {
    const container = document.getElementById('editRegionOptions');
    container.innerHTML = regionOptions.map(region => `
        <div class="option-item" data-value="${region.regionCode}">
            ${region.regionName}
        </div>
    `).join('');

    // 绑定点击事件
    container.querySelectorAll('.option-item').forEach(item => {
        item.addEventListener('click', (e) => {
            e.stopPropagation();
            item.classList.toggle('selected');
            updateEditSelectedRegions();
        });
    });
}

// 更新编辑弹窗的选中显示
function updateEditSelectedRegions() {
    const selected = [];
    document.querySelectorAll('#editRegionOptions .option-item.selected').forEach(item => {
        const region = regionOptions.find(r => r.regionCode === item.dataset.value);
        if (region) selected.push(region.regionName);
    });

    const displayText = selected.length > 0 ? selected.join('、') : '点击选择部位...';
    document.getElementById('editSelectedRegions').textContent = displayText;
    document.getElementById('editSelectedRegionsInput').value = selected.join('、');
}

// 切换编辑弹窗的下拉
function toggleEditRegionDropdown() {
    const options = document.getElementById('editRegionOptions');
    const isOpening = options.style.display !== 'block';
    options.style.display = isOpening ? 'block' : 'none';

    // 新增：切换激活状态
    document.querySelector('#editDialog .custom-multi-select').classList.toggle('active', isOpening);
}

// 点击外部关闭下拉
document.addEventListener('click', (e) => {
    if (!e.target.closest('.custom-multi-select')) {
        document.getElementById('editRegionOptions').style.display = 'none';
    }
});

// 更新选中值
function updateSelectedRegions() {
    const selected = [];
    document.querySelectorAll('.option-item.selected').forEach(item => {
        const region = regionOptions.find(r => r.regionCode === item.dataset.value);
        if (region) selected.push(region.regionName);
    });

    // 更新显示和隐藏字段
    const displayText = selected.length > 0 ? selected.join('、') : '点击选择部位...';
    document.querySelector('.selected-regions').textContent = displayText;
    document.getElementById('selectedRegions').value = selected.join('、');
}

// 切换下拉显示
function toggleRegionDropdown() {
    const options = document.getElementById('regionOptions');
    const isOpening = options.style.display !== 'block';
    options.style.display = isOpening ? 'block' : 'none';

    // 新增：切换激活状态
    document.querySelector('#addDialog .custom-multi-select').classList.toggle('active', isOpening);
}

// 点击外部关闭下拉
document.addEventListener('click', (e) => {
    if (!e.target.closest('.custom-multi-select')) {
        document.getElementById('regionOptions').style.display = 'none';
    }
});

// 加载数据
async function loadData() {
    const params = {
        pageSize: pageSize,
        pageNum: currentPage,
        params: {
            name: document.getElementById('searchName').value,
            phoneNumber: document.getElementById('searchPhoneNumber').value,
            address: document.getElementById('searchAddress').value
        }
    };

    try {
        const response = await fetch('/junxingtang/patient/pageQuery', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
            },
            body: JSON.stringify(params)
        });

        const result = await response.json();

        if (result.code === 200) {
            // 当前页码超出最大页码时自动修正
            if (result.data.pages > 0 && currentPage > result.data.pages) {
                currentPage = result.data.pages;
                loadData(); // 重新请求修正后的页码
                return; // 避免重复渲染
            }

            // 处理空数据情况
            if (result.data.total === 0) {
                currentPage = 1;
            }

            paginationData = result.data;
            renderTable(result.data);
            updatePagination();
        }
    } catch (error) {
        console.error('请求失败:', error);
    }
}

// 渲染表格
function renderTable(data) {
    const tbody = document.getElementById('tableBody');
    tbody.innerHTML = '';

    // 计算起始序号（核心修改）
    const startIndex = (currentPage - 1) * pageSize + 1;

    data.list.forEach((patient, index) => {
        const safeName = patient.name.replace(/'/g, "\\'");
        // 修改照片单元格逻辑
        const photoCell = patient.photoName ?
            `<div class="photo-wrapper">
                <img 
                    src="/junxingtang/patient/getPhoto?photoName=${encodeURIComponent(patient.photoName)}"
                    class="thumbnail"
                    onerror="handleImageError(this)"
                    onclick="(function(e) { 
                        e.stopPropagation(); 
                        showFullPhoto('${patient.photoName}', e); 
                    })(event)"
                >
            </div>` :
            ''; // 无照片时直接留空

        const row = `
            <tr onclick="handleRowClick(event, '${patient.id}', '${safeName}', this)">
                <td>${startIndex + index}</td>
                <td class="photo-cell">${photoCell}</td>
                <td>${patient.name}</td>
                <td>${patient.gender === 1 ? '男' : (patient.gender === 0 ? '女' : '-')}</td>
                <td>${patient.age}</td>
                <td>${patient.region || '-'}</td>
                <td>${patient.phoneNumber}</td>
                <td>${patient.address || '-'}</td>
                <td>${patient.remark || '-'}</td>
                <td>${patient.number}</td>
                <td>
                    <button onclick="event.stopPropagation();editPatient('${patient.id}')">编辑</button>
                    <button onclick="event.stopPropagation();deletePatient('${patient.id}')">删除</button>
                </td>
            </tr>
        `;
        tbody.innerHTML += row;
    });
}

// 全局图片错误处理
function handleImageError(img) {
    // 1. 移除错误图片请求
    const wrapper = img.parentNode;
    wrapper.removeChild(img);

    // 2. 创建错误提示
    const errorSpan = document.createElement('span');
    errorSpan.className = 'load-fail-tip';
    errorSpan.textContent = '加载失败';

    // 3. 添加到DOM
    wrapper.appendChild(errorSpan);
}

// 显示大图预览
function showFullPhoto(photoName, event) {
    const modal = document.getElementById('photoModal');
    const img = modal.querySelector('#fullPhoto');
    // 添加时间戳防止缓存
    img.src = `/junxingtang/patient/getPhoto?photoName=${encodeURIComponent(photoName)}&t=${Date.now()}`;
    // 错误处理
    img.onerror = function() {
        // this.src = '/junxingtang/img/error-placeholder.png';
        this.src = '#';
    };
    modal.style.display = 'flex';

    // 新增事件参数传递
    return function(photoName, event) {
        if (event) {
            event.stopPropagation(); // 阻止事件冒泡
        }
        const modal = document.getElementById('photoModal');
        const img = modal.querySelector('#fullPhoto');
        img.src = `/junxingtang/patient/getPhoto?photoName=${encodeURIComponent(photoName)}&t=${Date.now()}`;
        img.onerror = function() {
            this.src = '#';
        };
        modal.style.display = 'flex';
    }
}

// 关闭预览
function closePhotoModal() {
    document.getElementById('photoModal').style.display = 'none';
    document.getElementById('fullPhoto').src = '';
}

// 点击模态框背景关闭
document.getElementById('photoModal').addEventListener('click', function(e) {
    if (e.target === this) closePhotoModal();
});

// 更新分页信息
function updatePagination() {
    const pageInfo = document.getElementById('pageInfo');
    const prevBtn = document.getElementById('prevPage');
    const nextBtn = document.getElementById('nextPage');

    // 确保分页数据存在
    if (!paginationData) return;

    // 更新显示信息
    pageInfo.innerHTML = `第 ${currentPage} 页 / 共 ${paginationData.pages} 页（共 ${paginationData.total} 条）`;

    // 更新按钮状态（使用严格布尔值判断）
    prevBtn.disabled = !paginationData.hasPreviousPage;
    nextBtn.disabled = !paginationData.hasNextPage;

    // 调试日志
    console.log('分页状态:', {
        current: currentPage,
        hasPrev: paginationData.hasPreviousPage,
        hasNext: paginationData.hasNextPage
    });
}

// 分页操作
function changePage(step) {
    const newPage = currentPage + step;

    // 添加边界检查
    if (newPage < 1 || newPage > paginationData.pages) {
        console.log('无效页码:', newPage);
        return;
    }

    currentPage = newPage;
    console.log('正在加载:', currentPage);
    loadData();
}

// 搜索功能
function search() {
    currentPage = 1;
    loadData();
}

// 新增患者弹窗
function showAddDialog() {
    // 1.重置表单
    document.getElementById('addForm').reset();

    // 强制清除自定义下拉的选中状态（新增）
    document.querySelectorAll('.option-item.selected').forEach(item => {
        item.classList.remove('selected');
    });
    document.querySelector('.selected-regions').textContent = '点击选择部位...';
    document.getElementById('selectedRegions').value = '';

    // 2.重置照片预览
    document.getElementById('photoPreview').src = '#';
    document.getElementById('photoPreview').style.display = 'none';
    // 3.清空隐藏字段
    document.getElementById('photoName').value = '';

    // 4.显示弹窗
    document.getElementById('addDialog').style.display = 'flex';
}

function closeDialog() {

    document.getElementById('addForm').reset();

    // 新增：手动清除自定义下拉状态
    document.querySelectorAll('.option-item.selected').forEach(item => {
        item.classList.remove('selected');
    });
    document.querySelector('.selected-regions').textContent = '点击选择部位...';
    document.getElementById('selectedRegions').value = '';

    const preview = document.getElementById('photoPreview');
    preview.src = '#'; // 清空预览图
    preview.style.display = 'none'; // 隐藏预览区域
    document.getElementById('photoName').value = ''; // 清空UUID

    // 关闭弹框
    document.getElementById('addDialog').style.display = 'none';

    // 清除残留的下拉激活状态
    document.querySelector('#addDialog .custom-multi-select').classList.remove('active');
    document.getElementById('regionOptions').style.display = 'none';

    // 释放对象 URL 内存（重要！）
    if (preview.src.startsWith('blob:')) {
        URL.revokeObjectURL(preview.src);
    }
}

// 用户选择图片后立即上传
async function uploadPhoto(file) {
    const formData = new FormData();
    formData.append('file', file);

    try {
        const response = await fetch('/junxingtang/patient/uploadPhoto', {
            method: 'POST',
            body: formData,
        });
        const result = await response.json(); // 解析为JSON对象

        if (result.code === 200) {
            const uuid = result.data; // 从data字段获取UUID
            document.getElementById('photoName').value = uuid;
        } else {
            // 处理错误（如提示用户）
            console.error('上传失败:', result.message);
            alert('上传失败: ' + result.message);
        }
    } catch (error) {
        // 处理网络或解析错误
        console.error('请求异常:', error);
        alert('上传失败，请检查网络');
    }
}

async function handlePhotoUpload(event) {
    const file = event.target.files[0];
    if (!file) return;

    // 本地预览（即时显示，无需等待上传完成）
    const preview = document.getElementById('photoPreview');
    preview.style.display = 'block';
    preview.src = URL.createObjectURL(file);

    try {
        // 执行上传
        const response = await fetch('/junxingtang/patient/uploadPhoto', {
            method: 'POST',
            body: (() => {
                const formData = new FormData();
                formData.append('file', file);
                return formData;
            })()
        });

        const result = await response.json();

        if (result.code === 200) {
            // 存储UUID到隐藏字段
            document.getElementById('photoName').value = result.data;
            console.log('图片上传成功，UUID:', result.data);
        } else {
            throw new Error(result.message || '上传失败');
        }
    } catch (error) {
        // 错误处理
        console.error('上传失败:', error);
        alert('图片上传失败: ' + error.message);
        // 清除预览
        preview.style.display = 'none';
        preview.src = '#';
        // 清空文件选择
        event.target.value = '';
    } finally {
        // 释放内存
        URL.revokeObjectURL(preview.src);
        // 确保在上传完成后（无论成功与否）清理文件选择
        event.target.value = ''; // 清空文件选择框
    }
}

async function handleAddSubmit() {
    // 获取选中的部位名称（核心修改）
    const selectedRegions = Array.from(document.querySelectorAll('.option-item.selected'))
        .map(item => {
            const region = regionOptions.find(r => r.regionCode === item.dataset.value);
            return region ? region.regionName : null;
        })
        .filter(name => name)
        .join('、'); // 用顿号分隔

    const patient = {
        // 新增照片UUID字段
        photoName: document.getElementById('photoName').value || null,
        name: document.getElementById('addName').value.trim(),
        gender: parseInt(document.getElementById('addGender').value),
        age: parseInt(document.getElementById('addAge').value),
        region: selectedRegions || null, // 新增部位字段
        phoneNumber: document.getElementById('addPhone').value,
        address: document.getElementById('addAddress').value || null, // 新增住址
        remark: document.getElementById('addRemark').value || null, // 新增备注
        number: parseInt(document.getElementById('addNumber').value)
    };

    // 基础验证
    if (!patient.name) {
        alert('请输入患者姓名');
        return;
    }
    if (isNaN(patient.age) || patient.age < 0) {
        alert('请输入有效年龄');
        return;
    }
    if (!/^1[3-9]\d{9}$/.test(patient.phoneNumber)) {
        alert('请输入有效的手机号码');
        return;
    }
    if (!patient.number) {
        alert('请输入次数');
        return;
    }

    try {
        const response = await fetch('/junxingtang/patient/add', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
            },
            body: JSON.stringify(patient)
        });

        const result = await response.json();
        if (result.code === 200) {
            alert('新增成功');
            closeDialog();

            // 在 loadData 外层添加错误处理
            try {
                await loadData();// 添加 await 确保异步完成
            } catch (loadError) {
                console.error('数据刷新失败:', loadError);
            }
        } else {
            alert('新增失败：' + (result.message || '未知错误'));
        }
    } catch (error) {
        console.error('请求失败:', error);
        alert('网络请求异常，请稍后重试');
    }
}

// 编辑患者弹窗
async function editPatient(id) {
    currentEditId = id;
    try {
        // 获取患者详情
        const response = await fetch(`/junxingtang/patient/getById?id=${id}`);
        const result = await response.json();

        if (result.code === 200) {
            const data = result.data;

            // 填充照片信息
            const preview = document.getElementById('editPhotoPreview');
            if (data.photoName) {
                preview.src = `/junxingtang/patient/getPhoto?photoName=${encodeURIComponent(data.photoName)}`;
                preview.style.display = 'block';
            } else {
                preview.style.display = 'none';
            }
            document.getElementById('editPhotoName').value = data.photoName || '';

            // 填充表单
            document.getElementById('editId').value = data.id;
            document.getElementById('editName').value = data.name;
            document.getElementById('editGender').value = data.gender;
            document.getElementById('editAge').value = data.age;
            document.getElementById('editPhone').value = data.phoneNumber;
            document.getElementById('editAddress').value = data.address || ''; // 新增住址
            document.getElementById('editRemark').value = data.remark || ''; // 新增备注
            document.getElementById('editNumber').value = data.number;

            // 处理部位多选
            const selectedRegions = data.region ? data.region.split('、') : [];
            initEditRegionSelect(); // 初始化选项

            // 清除旧选中状态
            document.querySelectorAll('#editRegionOptions .option-item').forEach(item => {
                item.classList.remove('selected');
            });

            // 设置新选中状态
            selectedRegions.forEach(regionName => {
                const region = regionOptions.find(r => r.regionName === regionName);
                if (region) {
                    const item = document.querySelector(`#editRegionOptions .option-item[data-value="${region.regionCode}"]`);
                    if (item) item.classList.add('selected');
                }
            });

            updateEditSelectedRegions(); // 更新显示

            // 显示弹窗
            document.getElementById('editDialog').style.display = 'flex';
        }
    } catch (error) {
        console.error('获取详情失败:', error);
        alert('获取患者信息失败');
    }
}

// 编辑弹窗照片上传
async function handleEditPhotoUpload(event) {
    const file = event.target.files[0];
    if (!file) return;

    // 本地预览
    const preview = document.getElementById('editPhotoPreview');
    preview.style.display = 'block';
    preview.src = URL.createObjectURL(file);

    try {
        // 上传到服务器
        const formData = new FormData();
        formData.append('file', file);
        const response = await fetch('/junxingtang/patient/uploadPhoto', {
            method: 'POST',
            body: formData
        });
        const result = await response.json();

        if (result.code === 200) {
            document.getElementById('editPhotoName').value = result.data;
        }
    } catch (error) {
        console.error('照片上传失败:', error);
        preview.style.display = 'none';
    }
}

// 关闭编辑弹窗
function closeEditDialog() {
    document.getElementById('editForm').reset();

    // 重置照片预览
    const preview = document.getElementById('editPhotoPreview');
    preview.src = '#';
    preview.style.display = 'none';
    document.getElementById('editPhotoName').value = '';

    // 新增：手动清除编辑弹窗的下拉状态
    document.querySelectorAll('#editRegionOptions .option-item.selected').forEach(item => {
        item.classList.remove('selected');
    });
    document.getElementById('editSelectedRegions').textContent = '点击选择部位...';
    document.getElementById('editSelectedRegionsInput').value = '';

    document.getElementById('editDialog').style.display = 'none';
    currentEditId = null;

    // 清除残留状态
    document.querySelector('#editDialog .custom-multi-select').classList.remove('active');

    document.getElementById('editDialog').style.display = 'none';
    currentEditId = null;
}

// 处理编辑提交
async function handleEditSubmit() {
    const patient = {
        id: currentEditId,
        photoName: document.getElementById('editPhotoName').value || null,
        name: document.getElementById('editName').value.trim(),
        gender: parseInt(document.getElementById('editGender').value),
        age: parseInt(document.getElementById('editAge').value),
        region: document.getElementById('editSelectedRegionsInput').value || null,
        phoneNumber: document.getElementById('editPhone').value,
        address: document.getElementById('editAddress').value || null, // 新增住址
        remark: document.getElementById('editRemark').value || null, // 新增备注
        number: parseInt(document.getElementById('editNumber').value)
    };

    // 验证逻辑（与新增相同）
    if (!patient.name) {
        alert('请输入患者姓名');
        return;
    }
    if (isNaN(patient.age) || patient.age < 0) {
        alert('请输入有效年龄');
        return;
    }
    if (!/^1[3-9]\d{9}$/.test(patient.phoneNumber)) {
        alert('请输入有效的手机号码');
        return;
    }
    if (!patient.number) {
        alert('请输入次数');
        return;
    }

    try {
        const response = await fetch('/junxingtang/patient/update', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
            },
            body: JSON.stringify(patient)
        });

        const result = await response.json();
        if (result.code === 200) {
            alert('修改成功');
            closeEditDialog();
            loadData(); // 刷新列表
        } else {
            alert('修改失败：' + (result.message || '未知错误'));
        }
    } catch (error) {
        console.error('请求失败:', error);
        alert('网络请求异常，请稍后重试');
    }
}

async function deletePatient(id) {
    if (!confirm('确定要删除该患者吗？')) return;

    try {
        // 发送删除请求
        const response = await fetch(`/junxingtang/patient/delete?id=${encodeURIComponent(id)}`, {
            method: 'GET'
        });

        const result = await response.json();

        if (result.code === 200) {
            alert('删除成功');
            // 删除后智能调整页码（核心修复）
            const currentDataCount = paginationData.list.length;
            if (currentDataCount === 1) { // 当前页只剩最后一条
                currentPage = currentPage > 1 ? currentPage - 1 : 1;
            }
            loadData();
        } else {
            alert(`删除失败：${result.message || '未知错误'}`);
        }
    } catch (error) {
        console.error('删除请求失败:', error);
        alert('网络异常，请稍后重试');
    }
}

// 显示就诊记录弹窗
async function showConsultDetail(patientId, patientName) {
    currentPatientId = patientId;
    currentConsultPage = 1;

    // 更新弹窗标题
    document.getElementById('consultDialogTitle').textContent = `${patientName} 就诊记录`;

    await loadConsultData();
    document.getElementById('consultDialog').style.display = 'flex';
}

// 加载就诊数据
async function loadConsultData() {
    const params = {
        pageSize: consultPageSize,
        pageNum: currentConsultPage,
        params: {
            patientId: currentPatientId
        }
    };

    try {
        const response = await fetch('/junxingtang/consultation-record/pageQuery', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
            },
            body: JSON.stringify(params)
        });

        const result = await response.json();
        if (result.code === 200) {
            paginationDataConsult = result.data; // 存储分页数据
            renderConsultTable(result.data);
            updateConsultPagination(result.data);
        }
    } catch (error) {
        console.error('请求失败:', error);
        alert('获取就诊记录失败');
    }
}

// 渲染就诊表格
function renderConsultTable(data) {
    const tbody = document.getElementById('consultBody');
    tbody.innerHTML = '';

    if (data.list.length === 0) {
        tbody.innerHTML = `
            <tr>
                <td colspan="4" style="text-align:center; color:#999;">暂无就诊记录</td>
            </tr>
        `;
        return;
    }

    const startIndex = (currentConsultPage - 1) * consultPageSize + 1;

    data.list.forEach((consult, index) => {
        const row = `
            <tr class="consult-cell" onclick="handleConsultClick('${consult.id}', this, event)">
                <td>${startIndex + index}</td>
                <td>${consult.consultationDate}</td>
                <td>${consult.number}</td>
                <td>
                    <button onclick="event.stopPropagation();editConsultation('${consult.id}', '${currentPatientId}')">编辑</button>
                </td>
            </tr>
        `;
        tbody.innerHTML += row;
    });
}

// 更新就诊分页
function updateConsultPagination(data) {
    const pageInfo = document.getElementById('consultPageInfo');
    const prevBtn = document.querySelector('#consultDialog .pagination button:first-child');
    const nextBtn = document.querySelector('#consultDialog .pagination button:last-child');

    // 更新分页信息
    pageInfo.textContent = `第 ${data.pageNum} 页 / 共 ${data.pages} 页（共 ${data.total} 条）`;

    // 控制按钮状态
    prevBtn.disabled = !data.hasPreviousPage;
    nextBtn.disabled = !data.hasNextPage;
}

// 分页操作
function changeConsultPage(newPage) {
    // 确保数据有效性
    if (!paginationDataConsult || newPage < 1 || newPage > paginationDataConsult.pages) {
        console.log('无效页码:', newPage);
        return;
    }

    currentConsultPage = newPage;
    loadConsultData(); // 重新加载数据
}

// 关闭就诊弹窗
function closeConsultDialog() {
    document.getElementById('consultDialog').style.display = 'none';
    currentPatientId = null;
}

// 显示详情弹窗
async function showRegionDetail(consultationId) {
    try {
        console.log('开始请求就诊详情，ID:', consultationId);
        const response = await fetch(`/junxingtang/consultation-record/getConsultationRecordDetail?consultationId=${consultationId}`);
        if (!response.ok) throw new Error(`HTTP错误! 状态码: ${response.status}`);

        const result = await response.json();
        console.log('接口响应:', result);

        if (result.code === 200) {
            renderDetailTable(result.data);
            // 强制提升层级
            document.getElementById('detailDialog').style.cssText = 'display:flex; z-index:2000;';
        } else {
            throw new Error(result.message || '未知错误');
        }
    } catch (error) {
        console.error('获取详情失败:', error);
        alert(`加载失败：${error.message}`);
        throw error; // 向上抛出错误
    }
}

// 渲染详情表格
function renderDetailTable(data) {
    const tbody = document.getElementById('detailBody');
    tbody.innerHTML = '';

    data.forEach(item => {
        const row = `
            <tr>
                <td>${item.regionName}</td>
                <td>${item.number}</td>
            </tr>
        `;
        tbody.innerHTML += row;
    });

    // 空数据提示
    if (data.length === 0) {
        tbody.innerHTML = `
            <tr>
                <td colspan="2" style="text-align:center; color:#999;">暂无治疗部位记录</td>
            </tr>
        `;
    }
}

// 关闭详情弹窗
function closeDetailDialog() {
    document.getElementById('detailDialog').style.display = 'none';
}

// 修改就诊记录点击处理函数
function handleConsultClick(consultId, cell, event) {
    if (event) {
        event.stopPropagation();// 阻止事件冒泡到更高层元素
    }
    // 防抖处理（300ms内重复点击无效）
    if (clickTimer) {
        return;
    }

    clickTimer = setTimeout(async () => {
        clickTimer = null;
        try {
            const row = cell;
            await showRegionDetail(consultId);

            // 选中状态逻辑
            document.querySelectorAll('#consultDialog tr').forEach(r => {
                r.classList.remove('active');
            });
            row.classList.add('active');
        } catch (error) {
            console.error('处理点击时出错:', error);
        }

    }, 300);
}

// 新增函数：处理行点击事件
function handleRowClick(event, patientId, patientName, row) {
    // 排除图片和按钮点击
    if (event.target.tagName === 'IMG' ||
        event.target.tagName === 'BUTTON') {
        return;
    }

    // 原行点击逻辑
    handlePatientClick(patientId, patientName, row);
    showConsultDetail(patientId, patientName);
}

// 新增患者点击处理函数
function handlePatientClick(patientId, patientName, row) {
    // 清除所有激活状态
    document.querySelectorAll('#patientTable tr').forEach(r => {
        r.classList.remove('active');
    });

    // 设置当前行激活
    row.classList.add('active');

    // 显示就诊记录弹窗
    showConsultDetail(patientId, patientName);
}

// 显示新增就诊弹窗
async function showAddConsultDialog() {
    try {
        // 清空原有数据
        const tbody = document.getElementById('regionBody');
        tbody.innerHTML = '';
        currentConsultationData = []; // 清空缓存数据

        // 重置总次数显示
        document.getElementById('totalCount').textContent = '共使用0次';

        // 初始化新行
        addRegionRow('add'); // 明确指定新增弹窗

        // 获取部位列表
        const response = await fetch('/junxingtang/patient/getRegionList');
        const result = await response.json();

        if (result.code === 200) {
            regionOptions = result.data;
            initConsultForm();
            document.getElementById('addConsultDialog').style.display = 'flex';
            // 确保DOM更新后重新计算
            setTimeout(() => {
                const inputs = document.querySelectorAll('#regionBody .count-input');
                inputs.forEach(input => input.value = '');
                updateTotalCount();
            }, 0);
        }
    } catch (error) {
        console.error('获取部位列表失败:', error);
        alert('初始化表单失败');
        // 失败时仍显示弹窗并重置
        document.getElementById('addConsultDialog').style.display = 'flex';
        updateTotalCount();
    }
}

// 初始化表单
function initConsultForm() {
    const tbody = document.getElementById('regionBody');
    tbody.innerHTML = '';// 清空可能残留的行
    currentConsultationData = [];
    addRegionRow('add'); // 初始添加一行
    updateTotalCount();
}

// 新增部位行
function addRegionRow(dialogType = 'add') {
    const tbody = dialogType === 'edit'
        ? document.getElementById('editRegionBody')
        : document.getElementById('regionBody');

    const row = document.createElement('tr');
    row.innerHTML = `
        <td>
            <input type="hidden" class="detail-id" value=""><!-- 空值表示新增 -->
            <select class="region-select">
                <option value="">请选择部位</option>
                ${regionOptions.map(r =>
                    `<option value="${r.regionCode}">${r.regionName}</option>`
                ).join('')}
            </select>
        </td>
        <td>
            <input 
                type="number" 
                class="count-input" 
                min="0" 
                value=""
                oninput="${dialogType === 'edit' ? 'updateEditTotalCount' : 'updateTotalCount'}()"
            >
        </td>
    `;
    tbody.appendChild(row);
}

// 更新总次数统计
function updateTotalCount() {
    const inputs = document.querySelectorAll('.count-input');
    let total = 0;
    let validRows = 0;

    inputs.forEach(input => {
        const value = parseInt(input.value) || 0;
        if (value > 0) {
            total += value;
            validRows++;
        }
    });

    document.getElementById('totalCount').textContent = `共使用 ${total} 次`;
    return total;
}

// 处理提交
async function handleAddConsultSubmit() {
    // 新增验证
    if (!validateConsultRows('add')) {
        return;
    }
    const regionDetails = [];
    const rows = document.querySelectorAll('#regionBody tr');

    // 收集有效数据
    rows.forEach(row => {
        const regionCode = row.querySelector('.region-select').value;
        const number = parseInt(row.querySelector('.count-input').value);

        if (regionCode && !isNaN(number) && number > 0) {
            const region = regionOptions.find(r => r.regionCode === regionCode);
            regionDetails.push({
                regionCode: regionCode,
                regionName: region.regionName,
                number: number
            });
        }
    });

    if (regionDetails.length === 0) {
        alert('请至少填写一个有效的治疗部位');
        return;
    }

    const params = {
        patientId: currentPatientId,
        number: updateTotalCount(), // 总次数
        consultationDate: new Date().toISOString().slice(0, 19).replace('T', ' '),
        consultationRecordDetailList: regionDetails
    };

    try {
        const response = await fetch('/junxingtang/consultation-record/add', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
            },
            body: JSON.stringify(params)
        });

        const result = await response.json();
        if (result.code === 200) {
            alert('新增成功');
            closeAddConsultDialog();
            loadConsultData(); // 刷新就诊记录列表
            loadData(); // 刷新外层患者列表数据
        } else {
            throw new Error(result.message || '未知错误');
        }
    } catch (error) {
        console.error('提交失败:', error);
        alert(`提交失败：${error.message}`);
    }
}

// 关闭弹窗
function closeAddConsultDialog() {
    document.getElementById('addConsultDialog').style.display = 'none';
}

// 修改全局点击关闭逻辑
document.addEventListener('click', (e) => {
    // 新增：获取所有输入控件
    const isInput = e.target.matches('input, select, textarea');

    // 关闭新增弹窗下拉
    const addSelect = document.querySelector('#addDialog .custom-multi-select');
    if (!e.target.closest('#addDialog .custom-multi-select')) {
        const addOptions = document.getElementById('regionOptions');
        if (addOptions.style.display === 'block') {
            addOptions.style.display = 'none';
            document.querySelector('#addDialog .custom-multi-select').classList.remove('active');
        }
    }

    // 关闭编辑弹窗下拉
    const editSelect = document.querySelector('#editDialog .custom-multi-select');
    if (!e.target.closest('#editDialog .custom-multi-select')) {
        const editOptions = document.getElementById('editRegionOptions');
        if (editOptions.style.display === 'block') {
            editOptions.style.display = 'none';
            document.querySelector('#editDialog .custom-multi-select').classList.remove('active');
        }
    }

    // 新增：当点击其他输入控件时强制移除激活状态
    if (isInput) {
        addSelect.classList.remove('active');
        editSelect.classList.remove('active');
    }
});

// 打开编辑弹窗
async function editConsultation(consultationId, patientId) {
    try {
        // 1. 获取就诊详情
        const response = await fetch(`/junxingtang/consultation-record/getConsultationRecordDetail?consultationId=${consultationId}`);
        const result = await response.json();

        if (result.code === 200) {
            // 2. 存储全局变量
            currentConsultationId = consultationId;
            currentPatientId = patientId;
            currentEditDetails = result.data;

            // 3. 渲染编辑表单
            renderEditForm(result.data);
            document.getElementById('editConsultDialog').style.display = 'flex';
        }
    } catch (error) {
        console.error('打开编辑弹窗失败:', error);
        alert('加载详情失败');
    }
}

// 渲染编辑表单
function renderEditForm(details) {
    const tbody = document.getElementById('editRegionBody');
    tbody.innerHTML = '';

    // 动态生成行（支持回显）
    details.forEach(detail => {
        const row = document.createElement('tr');
        row.innerHTML = `
            <td>
                <input type="hidden" class="detail-id" value="${detail.id}">
                <select class="region-select">
                    ${regionOptions.map(opt => `
                        <option value="${opt.regionCode}" ${opt.regionCode === detail.regionCode ? 'selected' : ''}>
                            ${opt.regionName}
                        </option>
                    `).join('')}
                </select>
            </td>
            <td>
                <input 
                    type="number" 
                    class="count-input" 
                    value="${detail.number}"
                    min="0" 
                    oninput="updateEditTotalCount()"
                >
            </td>
        `;
        tbody.appendChild(row);
    });

    updateEditTotalCount(); // 更新统计
}

// 更新统计
function updateEditTotalCount() {
    let total = 0;
    document.querySelectorAll('#editRegionBody .count-input').forEach(input => {
        total += parseInt(input.value) || 0;
    });
    document.getElementById('editTotalCount').textContent = `共使用 ${total} 次`;
}

async function handleEditConsultSubmit() {
    // 新增验证
    if (!validateConsultRows('edit')) {
        return;
    }
    // 1. 收集数据
    const details = [];
    document.querySelectorAll('#editRegionBody tr').forEach(row => {
        const detailId = row.querySelector('.detail-id').value; // 从隐藏字段获取id
        const regionCode = row.querySelector('.region-select').value;
        const number = parseInt(row.querySelector('.count-input').value);
        const region = regionOptions.find(r => r.regionCode === regionCode);
        if (!region) {
            alert(`无效的部位代码：${regionCode}`);
            return;
        }
        if (regionCode && number > 0) {
            details.push({
                id: detailId || null, // 保留原始id，新增则为null
                regionCode: regionCode,
                regionName: region.regionName,
                number: number,
                consultationId: currentConsultationId
            });
        }
    });

    // 2. 构造请求体
    const params = {
        id: currentConsultationId,
        patientId: currentPatientId,
        number: document.getElementById('editTotalCount').textContent.match(/\d+/)[0], // 提取总次数
        consultationRecordDetailList: details
    };

    // 3. 发送请求
    try {
        const response = await fetch('/junxingtang/consultation-record/update', {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify(params)
        });

        const result = await response.json();
        if (result.code === 200) {
            alert('修改成功');
            closeEditConsultDialog();
            loadConsultData(); // 刷新就诊记录
            loadData();       // 刷新患者列表
        } else {
            throw new Error(result.message || '保存失败');
        }
    } catch (error) {
        console.error('保存失败:', error);
        alert(error.message);
    }
}

// 关闭弹窗
function closeEditConsultDialog() {
    // 清空编辑弹窗数据
    const editTbody = document.getElementById('editRegionBody');
    editTbody.innerHTML = ''; // 清空表格行
    document.getElementById('editTotalCount').textContent = '共使用0次'; // 重置总次数显示

    // 重置全局变量
    currentConsultationId = null;
    currentEditDetails = [];

    // 隐藏弹框
    document.getElementById('editConsultDialog').style.display = 'none';
}

// 新增通用验证函数
function validateConsultRows(dialogType = 'add') {
    const selector = dialogType === 'edit' ? '#editRegionBody tr' : '#regionBody tr';
    let isValid = true;
    let message = '';

    document.querySelectorAll(selector).forEach((row, index) => {
        const regionSelect = row.querySelector('.region-select');
        const countInput = row.querySelector('.count-input');

        // 空值检查
        if (!regionSelect.value && countInput.value) {
            isValid = false;
            message = `第${index + 1}行：请选择部位`;
            highlightInvalid(row);
        }
        // 反向空值检查
        else if (regionSelect.value && !countInput.value) {
            isValid = false;
            message = `第${index + 1}行：请输入次数`;
            highlightInvalid(row);
        }
        // 全空检查
        else if (!regionSelect.value && !countInput.value) {
            isValid = false;
            message = `第${index + 1}行：部位和次数均为空`;
            highlightInvalid(row);
        }
        // 次数有效性检查
        else if (countInput.value && parseInt(countInput.value) <= 0) {
            isValid = false;
            message = `第${index + 1}行：次数必须大于0`;
            highlightInvalid(row);
        }
    });

    if (!isValid) {
        alert('验证失败：' + message);
    }
    return isValid;
}

// 高亮无效行
function highlightInvalid(row) {
    row.style.backgroundColor = '#fff3f3';
    setTimeout(() => {
        row.style.backgroundColor = '';
    }, 2000);
}